package org.mcclone.splitter;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author McClone
 */
public class TxtSplitter extends Splitter {
    private String encoding;
    private String destDir;

    public TxtSplitter(int size) {
        super(size);
    }

    public TxtSplitter execute(File file) {
        if (StringUtils.isBlank(getDestDir())) {
            this.setDestDir(file.getAbsolutePath());
            logger.info("destDir is " + getDestDir());
        }
        try {
            DefaultFileNameStrategy fileNameStrategy = new DefaultFileNameStrategy(file, destDir);
            LineIterator lineIterator = FileUtils.lineIterator(file, encoding);
            List<String> lines = new ArrayList<>(getSize());
            while (lineIterator.hasNext()) {
                org.mcclone.splitter.CollectionUtils.addToCollection(lines, lineIterator, getSize());
                FileUtils.writeLines(new File(fileNameStrategy.generate()), encoding, lines);
                lines.clear();
            }
            if (CollectionUtils.isNotEmpty(lines)) {
                FileUtils.writeLines(new File(fileNameStrategy.generate()), encoding, lines);
                lines.clear();
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return this;
    }

    public TxtSplitter setEncoding(String encoding) {
        this.encoding = encoding;
        return this;
    }

    public TxtSplitter setDestDir(String destDir) {
        this.destDir = destDir;
        return this;
    }

    public String getDestDir() {
        return destDir;
    }
}
